package com.glacier.yuyuan.common.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * date 2022-10-25 10:06
 * 日期打印拦截器
 *
 * @author glacier
 * @version 1.0
 */
public class LogHandlerInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogHandlerInterceptor.class);

    /**
     * 当前线程共享变量
     */
    private static final ThreadLocal<StopWatch> STOP_WATCH_THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        STOP_WATCH_THREAD_LOCAL.set(stopWatch);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        StopWatch stopWatch = STOP_WATCH_THREAD_LOCAL.get();
        stopWatch.stop();
        LOGGER.info("请求地址: {} {}", request.getRequestURL(), request.getMethod());
        LOGGER.info("远程地址: {}", request.getRemoteAddr());
        LOGGER.info("耗时：{} ms", stopWatch.getTotalTimeMillis());
        STOP_WATCH_THREAD_LOCAL.remove();
    }
}
